package com.wlc.service.impl;

import com.wlc.mapper.UserMapper;
import com.wlc.pojo.LoginInfo;
import com.wlc.pojo.PageResult;
import com.wlc.pojo.User;
import com.wlc.service.UserService;
import com.wlc.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户服务实现类
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Override
    public PageResult<User> findUserList(String username, String employeeName, Integer page, Integer size) {
        log.info("查询用户列表分页: username={}, employeeName={}, page={}, size={}",
                username, employeeName, page, size);

        // 参数校验和默认值
        if (page == null || page < 1) page = 1;
        if (size == null || size < 1) size = 10;
        if (size > 100) size = 100;

        // 查询总数
        Long total = userMapper.selectUserCount(username, employeeName);

        // 查询分页数据
        List<User> users = userMapper.selectUserList(username, employeeName, (page - 1) * size, size);

        return new PageResult<>(total, users);
    }

    @Autowired
    private UserMapper userMapper;

    /**
     * 根据ID查询用户
     */
    @Override
    public User findById(Long id) {
        log.info("根据ID查询用户: {}", id);
        return userMapper.selectById(id);
    }

    /**
     * 根据用户名查询用户
     */
    @Override
    public User findByUsername(String username) {
        log.info("根据用户名查询用户: {}", username);
        return userMapper.selectByUsername(username);
    }

    /**
     * 查询用户列表（分页）
     */
    @Override
    public PageResult<User> findList(String username, String employeeName, Integer page, Integer size) {
        log.info("查询用户列表: username={}, employeeName={}, page={}, size={}",
                username, employeeName, page, size);

        // 查询所有数据
        List<User> userList = userMapper.selectList(username, employeeName);

        // 手动分页
        Long total = (long) userList.size();
        if (page != null && size != null) {
            int fromIndex = (page - 1) * size;
            int toIndex = Math.min(fromIndex + size, userList.size());
            if (fromIndex < userList.size()) {
                userList = userList.subList(fromIndex, toIndex);
            } else {
                userList = List.of();
            }
        }

        return new PageResult<>(total, userList);
    }

    /**
     * 新增用户
     */
    @Override
    @Transactional
    public void save(User user) {
        log.info("新增用户: {}", user.getUsername());

        // 校验用户名是否已存在
        User existingUser = userMapper.selectByUsername(user.getUsername());
        if (existingUser != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 设置默认值
        user.setIsEnabled(1);
        user.setIsAccountNonExpired(1);
        user.setIsAccountNonLocked(1);
        user.setIsCredentialsNonExpired(1);
        // 移除 isDeleted 设置
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        int result = userMapper.insert(user);
        if (result <= 0) {
            throw new RuntimeException("新增用户失败");
        }

        log.info("新增用户成功: {}", user.getUsername());
    }

    /**
     * 更新用户
     */
    @Override
    @Transactional
    public void update(User user) {
        log.info("更新用户: {}", user.getId());

        // 校验用户是否存在
        User existingUser = userMapper.selectById(user.getId());
        if (existingUser == null) {
            throw new RuntimeException("用户不存在");
        }

        // 校验用户名是否被其他用户使用
        if (user.getUsername() != null) {
            User userByUsername = userMapper.selectByUsername(user.getUsername());
            if (userByUsername != null && !userByUsername.getId().equals(user.getId())) {
                throw new RuntimeException("用户名已被其他用户使用");
            }
        }

        user.setUpdateTime(LocalDateTime.now());
        int result = userMapper.update(user);
        if (result <= 0) {
            throw new RuntimeException("更新用户失败");
        }

        log.info("更新用户成功: {}", user.getId());
    }

    /**
     * 删除用户
     */
    @Override
    @Transactional
    public void deleteById(Long id) {
        log.info("删除用户: {}", id);

        User user = userMapper.selectById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 改为物理删除
        int result = userMapper.deleteById(id);
        if (result <= 0) {
            throw new RuntimeException("删除用户失败");
        }

        log.info("删除用户成功: {}", id);
    }

    /**
     * 启用/禁用用户
     */
    @Override
    @Transactional
    public void updateStatus(Long id, Integer status) {
        log.info("更新用户状态: id={}, status={}", id, status);

        User user = userMapper.selectById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        if (status != 0 && status != 1) {
            throw new RuntimeException("状态值不合法");
        }

        int result = userMapper.updateStatus(id, status);
        if (result <= 0) {
            throw new RuntimeException("更新用户状态失败");
        }

        log.info("更新用户状态成功: id={}, status={}", id, status);
    }

    @Override
    public LoginInfo login(User user) {
        //1.调用mapper接口，根据员工用户名和密码查询员工信息
        User e=userMapper.selectByUsernameAndPassword(user);
        //2.判断是否存在这个员工，如果存在，组装员工登录信息
        if(e!=null){

            Map<String, Object> claims= new HashMap<>();
            claims.put("id",e.getId());
            claims.put("username",e.getUsername());
            String jwt = JwtUtils.generateToken(claims);
            return new LoginInfo(e.getId(),e.getUsername(),jwt);
//            return new LoginInfo(e.getId(),e.getUsername(),"");
        }
        //3.不存在，返回null
        return null;
    }
}